package com.kl.drs.action;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.kl.drs.bean.bo.BankResportBO;
import com.kl.drs.bean.bo.CCBLCContBO;
import com.kl.drs.bean.bo.CCBRetDataBO;
import com.kl.drs.bean.bo.DrsAsynchTaskBO;
import com.kl.drs.bean.bo.DrsLdcomRelationBO;
import com.kl.drs.bean.bo.LaAgentBO;
import com.kl.drs.bean.bo.RelationIdBO;
import com.kl.drs.bean.bo.RelationMappingBO;
import com.kl.drs.bean.bo.TaskInfoBO;
import com.kl.drs.bean.dto.CoreInfoDTO;
import com.kl.drs.common.BusinessKey;
import com.kl.drs.service.BankButtjointService;
import com.kl.drs.service.DrsAsynchTaskService;
import com.kl.drs.service.RecordingAnalysisService;
import com.kl.drs.service.TaskInfoService;
import com.kl.drs.util.ConfigsUtil;
import com.kl.drs.util.CopyFileUtil;
import com.kl.drs.util.DateUtils;
import com.kl.drs.util.DelFileUtil;
import com.kl.drs.util.Log4jUtils;
import com.kl.drs.util.VideoFileUtils;
import com.kl.drs.util.XmlUtils;

@Service("bankButtjointAction ")
public class BankButtjointAction {
	@Autowired
	private BankButtjointService bankButtjointService;
	@Autowired
	private TaskInfoService taskInfoService;
	@Autowired
	private RecordingAnalysisService recordingAnalysisService;
	@Autowired
	private DrsAsynchTaskService drsAsynchTaskService;
	// 前置机视频文件路径
	@Value("${ccb.link.ftp.path}")
	private String ftpPath;
	// 本地服务器路径
	@Value("${video.path}")
	private String videoPath;
	// 建行备份文件
	@Value("${ccb.ftp.copy.path}")
	private String copyFile;
	//保险公司编号
	@Value("${subinsurer.code}")
	private String subInsurerCode;
	//建行编码
	@Value("${ccb.code}")
	private String ccbBankCode;
	//保险公司总代码
	@Value("${insurer.code}")
	private String insurerCode;
	
	/**
	 * 对接建行信息,进行参数的处理
	 * @throws ParseException 
	 * 
	 */

	public Map bankButtjoint(CCBLCContBO ccbLCContBO)
			throws ClientProtocolException, IOException, ParseException {
		Map<String, String>resultXML=new HashMap<String, String>();
		TaskInfoBO taskInfoBO = new TaskInfoBO();
		Map result = new HashMap();
		String dateStr = DateUtils.formatDate("yyyyMMdd");
//		CCBLCContBO ccbLCCont=null;
		CoreInfoDTO ccbLCCont=null;
		 String contNo;
		 String businessNo=ccbLCContBO.getBusinessNo();
		Log4jUtils.logDebug("ccbLCContBO-------:"+ccbLCContBO.toString());
		String businessServiceNo;
		//判断是否传入投保单号
		Map<String, String> queryMap =new HashMap<String, String>();
		if(null == ccbLCContBO.getContNo() || "".equals(ccbLCContBO.getContNo())){
			//判断交易服务名为A03812115为原投保交易
			String tranServiceName=ccbLCContBO.getTranServiceName();
			if(tranServiceName.equals(BusinessKey.Ins_Co_Jrnl_No)){
				//此时的交易流水号为BusinessSerialNo(保险公司方)
				businessServiceNo=ccbLCContBO.getBusinessSerialNo();
				queryMap.put("transno", businessServiceNo);
			}else{
				queryMap.put("transno", businessNo);
			}
		}else{	
			queryMap.put("polno", ccbLCContBO.getContNo());
		}
		ccbLCCont = bankButtjointService.queryCoreLCbyBusinessNo(queryMap);
		if(null == ccbLCCont){
			ccbLCCont = bankButtjointService.queryCoreLBbyBusinessNo(queryMap);
		}
		//modify by zyl 20180620 添加对保单信息的空置判断，解决读取文件异常导致程序中断，执行完文件不能正常删除，进入死循环bug，
		if(ccbLCCont == null){
			Log4jUtils.logDebug("核心无对应的保单信息异常："+ccbLCContBO.toString());
		}else{
			/*客户出生日期*/
			String customerBirthday=DateUtils.date2Str(ccbLCCont.getAppntBirthday(),DateUtils.date_sdf);
			Log4jUtils.logDebug("customerBirthday:"+customerBirthday);
			taskInfoBO.setCustomerBirthday(customerBirthday);
			/*业务识别号*/
			contNo=ccbLCCont.getPolNo();
			taskInfoBO.setBusinessNo(contNo);
			/* 客户名称 */
			String customerName = ccbLCCont.getAppntName();
			taskInfoBO.setCustomerName(customerName);
			/* 获取客户的证件号码 */
			String customerCardNo = ccbLCCont.getAppntIdNo();
			taskInfoBO.setCustomerCardNo(customerCardNo);
			/* 证件类型代码 */
			String customerCardType = ccbLCCont.getAppntIdType();
			Log4jUtils.logDebug("证件号码类型："+customerCardType);
			//转换证件编码
			String customerCardTypes = bankButtjointService.queryIdcodeByUnion(customerCardType,
					BusinessKey.BANK_BUTTJIONT_CODE, BusinessKey.BANK_BUTTJIONT_CIITC);
			taskInfoBO.setCustomerCardType(Integer.parseInt(customerCardTypes));
			//通过保单号查询险种信息
			if(ccbLCCont.getPayIntv()!=null&&ccbLCCont.getRiskCode()!=null){
				int paymentTermInt = ccbLCCont.getPayIntv();
				/* 缴费方式转换*/
				/*
				 * 1 -- 不定期交, 0 -- 趸交, 1 -- 月交 3 -- 季交 6 -- 半年交 12 -- 年交
				 */
				if (paymentTermInt == 0) {
					paymentTermInt = BusinessKey.CIITC_WHOLE_PAY;
				} else if (paymentTermInt == 1) {
					paymentTermInt = BusinessKey.CIITC_IRREGULAR_PAY;
				} else {
					paymentTermInt = BusinessKey.CIITC_PERIOD_PAY;
				}
				taskInfoBO.setPaymentTerm(paymentTermInt);
				Log4jUtils.logDebug("paymentTermInt:"+paymentTermInt);	
				/* 险种编码*/
				String riskCode = ccbLCCont.getRiskCode();
				taskInfoBO.setProductCode(riskCode);
			}
			
			/* 保险公司编号 */
			taskInfoBO.setSubInsurerCode(subInsurerCode);
			/* 保险公司流水号 */
			String businessSerialNo = ccbLCContBO.getBusinessSerialNo();
			taskInfoBO.setBusinessSerialNo(businessSerialNo);
			/* 保险业务来源 */
			taskInfoBO.setTaskSource(1);
			// 视频文件的获取		
			try {
				
				File file = new File(ftpPath);
				String [] fileName = file.list();
				for(String videoName:fileName)
				{
					//String[] videoList=videoName.split("_");
					//String videoNames = videoList[0];
					String videoNames = videoName.substring(0,videoName.length()-4);
					if( businessNo.equalsIgnoreCase(videoNames)){
						taskInfoBO.setVideoName(videoName);
						Log4jUtils.logDebug("视频名称:"+taskInfoBO.getVideoName());
						String videoType=videoName.substring(videoName.length()-3, videoName.length());
						String videoSuffix=videoName.substring(videoName.indexOf(".")+1, videoName.length());
						Log4jUtils.logDebug("type:"+videoType);
						taskInfoBO.setVideoType(videoType);
						//进行文件的复制
						String ftpVideoPath=ftpPath+taskInfoBO.getVideoName();
						/*获取视频文件的长度*/
						File fileLength=new File(ftpVideoPath);
						taskInfoBO.setFileLength(fileLength.length());
						/*获取视频文件的时长*/
						taskInfoBO.setFileTime(VideoFileUtils.getVideoFileTime(ftpVideoPath));
						String videoFilePath=videoPath+dateStr+File.separator+taskInfoBO.getVideoName();
						CopyFileUtil.copyOneFile(ftpVideoPath, videoFilePath);
						/* 获取路径 */
						taskInfoBO.setVUrl(dateStr);
						//String subBankCode = ccbLCCont.getBankBranch();
						//taskInfoBO.setSubBankCode(subBankCode);
						String counterId = ccbLCCont.getBankOperator();
						taskInfoBO.setCounterId(counterId);
						/* 建行编码 */
						taskInfoBO.setBankCode(ccbBankCode);
						/* 上传类型 */
						taskInfoBO.setUpdateTaskType(2);
						/* 保险公司总代码 */
						taskInfoBO.setInsurerCode(insurerCode);
						// 获取建行机构编码然后进行转码处理
//						RelationMappingBO relationMappingBO;
//						result.put("relationCode", subBankCode);
//						result.put("relationType", BusinessKey.BANK_BUTTJIONT_CCB);
//						relationMappingBO = this.bankButtjointService.queryMappingTypeRelService(result);
//						// Log4jUtils.logDebug("关联机构编码为"+relationMappingBO.getSysCode());
//						if (relationMappingBO == null) {
//							RelationMappingBO relationMapping = new RelationMappingBO();
//							relationMapping.setRelationCode((String) result.get("relationCode"));
//							relationMapping.setRelationType((String) result.get("relationType"));
//							relationMapping.setSysCode(BusinessKey.BANK_BUTTJIONT_CCB);
//							this.bankButtjointService.addMappingTypeRelService(relationMapping);
//							relationMappingBO = this.bankButtjointService.queryMappingTypeRelService(result);
//						}
//						Map<String, String> conMap = new HashMap<String, String>();
//						conMap.put("sysCode", relationMappingBO.getSysCode());
//						conMap.put("relationType", BusinessKey.BANK_BUTTJIONT_CIITC);
//						RelationMappingBO relationMapping = this.bankButtjointService.queryMappingTypeRelService(conMap);
//						Log4jUtils.logDebug("中国保信关联机构编码为"+ relationMapping.getRelationCode());
//						taskInfoBO.setSubBankCode(relationMapping.getRelationCode());
//						Log4jUtils.logDebug("taskInfoBO.getSubBankCode():"+ taskInfoBO.getSubBankCode());
						//taskInfoBO.setCounterId(counterId);
						//根据查询核心的机构编码查询，对应的分公司信息
						String manageCom = ccbLCCont.getManageCom();
						if(StringUtils.isBlank(manageCom)){
							Log4jUtils.logDebug("从核心获取的机构编码manageCom为空");
						}else{
							DrsLdcomRelationBO queryDrsLdcomRel = this.bankButtjointService.queryDrsLdcomRel(manageCom);
							if(queryDrsLdcomRel != null){
								//分行编码
								taskInfoBO.setSubBankCode(queryDrsLdcomRel.getSubBankCode());
								//保险公司代码（省级分公司） 
								taskInfoBO.setSubInsurerCode(queryDrsLdcomRel.getSubInsurerCode());
							}
						}
						//1-保单号，2-投保单号，3-其他  目前邮储的都是投保单号，建行是保单号 20180628
						//查询销售人员名称20180628
						Map<String, String> conMap=new HashMap<String, String>();
						conMap.put("bankCode",ccbLCCont.getBankCode());
						conMap.put("bankBranch",ccbLCCont.getBankBranch());
						conMap.put("bankNode",ccbLCCont.getBankNode());
						LaAgentBO laAgentBO = this.bankButtjointService.queryAgentName(conMap);
						if(laAgentBO != null){
							taskInfoBO.setCounterName(laAgentBO.getAgentName());
							taskInfoBO.setCounterPhone(laAgentBO.getAgentMobile());
						}
						taskInfoBO.setRecordTime(DateUtils.formatTime("yyyyMMddHHmmss"));//视频录制日期
						/* 业务识别号类型*/
						taskInfoBO.setBusinessType(BusinessKey.CIITC_CONTNO_BUSINESSTYPE);
						int createFlag = this.recordingAnalysisService.createOrUpdateRecording(taskInfoBO);
						if (createFlag < 1) {
							result.put("message", "上传任务失败！");
						} else {
							DrsAsynchTaskBO drsAsynchTask = new DrsAsynchTaskBO();
							drsAsynchTask.setBusinessNo(taskInfoBO.getBusinessNo());
							drsAsynchTask.setBusinessSerialNo(taskInfoBO.getBusinessSerialNo());
							drsAsynchTask.setTaskType(BusinessKey.ASYNCH_TYPE_UB);
							drsAsynchTask.setStatus(BusinessKey.ASYNC_TASK_STATUS_WAIT);
							drsAsynchTaskService.addAsynchTask(drsAsynchTask);
							
							CCBRetDataBO ccbRetData=new CCBRetDataBO("1","success!");
							BankResportBO resport=new BankResportBO(ccbRetData);
							String xmlStr= XmlUtils.convertToXml(resport);
							resultXML.put("resultXML", xmlStr);
							Log4jUtils.logDebug("resultMap:"+resultXML.get("resultXML"));
							Log4jUtils.logDebug("结束操作，进行备份");
							CopyFileUtil.copyOneFile(ftpVideoPath, copyFile+dateStr+File.separator+taskInfoBO.getVideoName());
							Log4jUtils.logDebug("**************备份文件结束*****************");
							DelFileUtil.deleteOneFile(ftpVideoPath);
							Log4jUtils.logDebug("**************删除文件结束*****************");
							
							return resultXML;
						}
						
					}
				}	
				
			} catch (Exception e) {
				Log4jUtils.logError("bankButtjoint","获取视频异常:"+e.getMessage(), e);
			}
		}
		CCBRetDataBO ccbRetData=new CCBRetDataBO("2", "fail!");
		BankResportBO resport=new BankResportBO(ccbRetData);
		String xmlStr= XmlUtils.convertToXml(resport);
		resultXML.put("resultXML", xmlStr);
		return resultXML;
	}
}
